<template>
  <basic-dialog
    title="修改密码"
    :width="550"
    :loading="loading"
    :visible="visible"
    @closed="handleClosed"
    @submit="handleSubmit"
  >
    <el-form
      ref="formRef"
      :key="formKey"
      :model="formState"
      label-position="right"
      :label-width="100"
      :rules="rules"
      require-asterisk-position="right"
    >
      <el-form-item
        :error="passwordState.pwdError"
        label="原密码"
        class="mb-7"
        prop="old_password"
      >
        <basic-password-input
          v-model="formState.old_password"
          placeholder="请输入原密码"
          autocomplete="off"
          @blur="passwordState.pwdError = ''"
        />
      </el-form-item>
      <el-form-item
        ref="newPasswordRef"
        label="新密码"
        prop="new_password"
        class="new_password"
        :error="passwordState.newPwdError"
      >
        <basic-password-input
          v-model="formState.new_password"
          placeholder="请输入新密码"
          autocomplete="off"
          @blur="passwordState.newPwdError = ''"
        />
        <span
          v-if="!formState.new_password && !newPasswordValidateState"
          class="text-xs text-[#868d9d] mt-2"
          >请输入8-20个字符，可包含英文字母、数字和标点符号（除空格）</span
        >
        <template v-if="newPasswordValidateState" #error="{ error }">
          <div class="el-form-item__error">
            {{ error }}
          </div>
        </template>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirm_password">
        <basic-password-input
          v-model="formState.confirm_password"
          autocomplete="off"
          placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
  </basic-dialog>
</template>
<script lang="ts" setup>
import type { FormInstance, FormItemInstance, FormItemRule } from 'element-plus'

import { ResultEnum } from '@/apis/http/httpEnum'

interface IProps {
  visible: boolean
}

interface IEmits {
  // 更新 显示状态
  (event: 'update:visible', value: boolean): void
}

interface FormState {
  old_password: string
  new_password: string
  confirm_password: string
}

const emit = defineEmits<IEmits>()
withDefaults(defineProps<IProps>(), {})
const formRef = ref<FormInstance>()
const loading = ref(false)
const formKey = ref(Date.now())

const formState = reactive<FormState>({
  old_password: '',
  new_password: '',
  confirm_password: ''
})
const passwordState = reactive({
  pwdError: '',
  newPwdError: ''
})

const newPasswordRef = ref<FormItemInstance>()

const newPasswordValidateState = computed(
  () => !!newPasswordRef.value?.validateState
)

const validatePass2 = (_, value: any) => {
  if (!value) {
    return new Error('请再次输入新密码')
  }
  if (value !== formState.new_password) {
    return new Error('两次密码输入不一致')
  }
  return true
}
const rules: Record<keyof FormState, FormItemRule[]> = {
  old_password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      trigger: 'blur',
      validator: passwordValidate
    }
  ],
  new_password: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      trigger: 'blur',
      validator(_, value) {
        if (value === formState.old_password) {
          return new Error('新密码不能与原密码相同')
        }
        return true
      }
    },
    {
      trigger: 'blur',
      validator: passwordValidate
    }
  ],
  confirm_password: [
    { required: true, trigger: 'blur', validator: validatePass2 }
  ]
}

/**
 * 保存方法
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  loading.value = true
  passwordState.pwdError = ''
  passwordState.newPwdError = ''
  changePasswordApi(formState)
    .then((res: any) => {
      if (res.code === ResultEnum.SUCCESS) {
        ToastUtils.success('修改成功')
        emit('update:visible', false)
      } else if (res.code === ResultEnum.WRONG_OLD_PASSWORD) {
        passwordState.pwdError = '原密码不正确，请重新输入'
      } else if (res.code === ResultEnum.WRONG_COMMON_PASSWORD) {
        passwordState.newPwdError = '新密码不能与原密码相同'
      } else {
        ToastUtils.error((res.message as string) || '')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * @description dialog 关闭前事件
 */
const handleClosed = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  passwordState.newPwdError = ''
  passwordState.pwdError = ''
  formKey.value = Date.now()
}
</script>

<style lang="scss" scoped>
.new_password {
  :deep(.el-form-item__content) {
    height: 72px;
    align-items: flex-start;
    .el-form-item__error {
      top: 45%;
    }
  }
}
</style>
